﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Think.Lenovo.Com.Models.NewsModel;
using Think.Lenovo.Com.DataAccess.NewsInfo;
using Think.Lenovo.Com.DataAccess;
using System.Data;
using Think.Lenovo.Com.Models.Users;

namespace Think.Lenovo.Com.Views.News
{
    public partial class ViewNewsAdd : System.Web.UI.Page
    {

        public string filePath = HttpRuntime.AppDomainAppVirtualPath;

        public string rel = string.Empty;

        NewsInfo newsinfo = new NewsInfo();
        Roles roles = new Roles();
        ViewUserModel model = new ViewUserModel();
        protected void Page_Load(object sender, EventArgs e)
        {
            model = (ViewUserModel)Session["User"];
            if (!Page.IsPostBack)
            {
                Bind_Right();

                try
                {
                    if (Int32.Parse(Request.QueryString["id"].ToString()) > 0)
                    {
                        Bing_News(Int32.Parse(Request.QueryString["id"].ToString()));
                        btn_add.Text = "更新";
                    }
                }
                catch (Exception ex)
                {
                    // throw;
                }
            }
        }

        /// <summary>
        /// 绑定新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void Bing_News(int id)
        {
            NewsModel nm = newsinfo.GetNewsInfo(id);

            txt_title.Text = nm.Title;
            txt_abbTitle.Text = nm.ABBTitle;
            editor.Value = nm.Content;
            string[] right = nm.BrowseRight.ToString().Split(',');
            txt_Abstracts.Text = nm.Abstracts;
            txt_author.Text = nm.Author;
            txt_source.Text = nm.Source;
            txt_target.Text = nm.Target;
            txt_Taxis.Text = nm.Taxis.ToString();
            txt_keyword.Text = nm.Keyword;
            txt_Integral.Text = nm.Integral.ToString();
            lbl_img.Text = nm.AbbPic;

            if(nm.TuiJian == 1)
            {
                cb_tuijian.Checked = true;
            }
            if (nm.TouTiao == 1)
            {
                cb_toutiao.Checked = true;
            }

            if (nm.TiaoZhuan == 1)
            {
                cb_tiaozhuan.Checked = true;
            }

            if (nm.JiaCu == 1)
            {
                cb_jiacu.Checked = true;
            }

            if (nm.Sign == 1)
            {
                sign.Items[0].Selected = true;
            }
            else
            {
                sign.Items[1].Selected = true;
            }

            if (nm.Feedback == 1)
            {
                fankui.Items[0].Selected = true;
            }
            else
            {
                fankui.Items[1].Selected = true;
            }



            foreach (string str in right)
            {
                for (int i = 0; i < cbl_right.Items.Count; i++)
                {
                    if (this.cbl_right.Items[i].Value == str)
                    {
                        this.cbl_right.Items[i].Selected = true;
                    }
                }
            }
        }

        protected long AddNews(NewsModel newsModel)
        {
            return newsinfo.AddNews(newsModel);
        }

        public void Bind_Right()
        {
            cbl_right.DataSource = roles.GetRoles();
            cbl_right.DataBind();
        }

        protected void btn_add_Click(object sender, EventArgs e)
        {
            try
            {
                if (Request.QueryString.Count > 0)
                {
                    UpDate();
                }
                else
                {
                    add();
                }
            }
            catch (Exception ex)
            {
                // throw;
            }
        }


        /// <summary>
        /// 添加
        /// </summary>
        public void add()
        {
            NewsModel newsModel = new NewsModel();
            newsModel.Title = txt_title.Text;
            newsModel.ABBTitle = txt_abbTitle.Text;

            if (cb_tuijian.Checked)
            {
                newsModel.TuiJian = 1;
            }
            else
            {
                newsModel.TuiJian = 0;
            }

            if (cb_tiaozhuan.Checked)
            {
                newsModel.TiaoZhuan = 1;
            }
            else
            {
                newsModel.TiaoZhuan = 0;
            }

            if (cb_toutiao.Checked)
            {
                newsModel.TouTiao = 1;
            }
            else
            {
                newsModel.TouTiao = 0;
            }

            if (cb_jiacu.Checked)
            {
                newsModel.JiaCu = 1;
            }
            else
            {
                newsModel.JiaCu = 0;
            }

            if (fankui.Items[0].Selected == true)
            {
                newsModel.Feedback = 1;
            }
            else
            {
                newsModel.Feedback =0;
            }

            if (sign.Items[0].Selected == true)
            {
                newsModel.Sign = 1;
            }
            else
            {
                newsModel.Sign = 0;
            }

            

            // newsModel.Tree = Int32.Parse(DDL_LanMu.SelectedValue);
            newsModel.Source = txt_source.Text;
            newsModel.Target = txt_target.Text;
            newsModel.Taxis = Int32.Parse(txt_Taxis.Text);
            //newsModel.AbbPic = txt_abbPic.Text;
            newsModel.Abstracts = txt_Abstracts.Text;
            newsModel.Keyword = txt_keyword.Text;
            newsModel.Content = editor.Value;
            newsModel.Author = txt_author.Text;
            newsModel.ReleaseDate = DateTime.Now;
            newsModel.Integral = Int32.Parse(txt_Integral.Text);
            newsModel.Types = Int32.Parse(DDL_LanMu.SelectedValue);
            newsModel.BrowseTime = 0;
            if (FileUpload1.FileName != null)
            {
                UploadImage(FileUpload1);
            }
            newsModel.AbbPic = rel;

            newsModel.AddUserId = model.Id;
            newsModel.AreaId = model.CompanyRegion;

            //获取选中权限
            foreach (ListItem item in this.cbl_right.Items)
            {
                if (item.Selected == true)
                {
                    newsModel.BrowseRight += item.Value + ",";
                }
            }

            if (AddNews(newsModel) > 0)
            {
                Response.Write("<script>alert('添加成功');location.href=location.href;</script>");
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        public void UpDate()
        {
            NewsModel newsModel = new NewsModel();

            newsModel.Id = Int32.Parse(Request.QueryString["id"].ToString());
            newsModel.Title = txt_title.Text;
            newsModel.ABBTitle = txt_abbTitle.Text;

            if (cb_tuijian.Checked)
            {
                newsModel.TuiJian = 1;
            }
            else
            {
                newsModel.TuiJian = 0;
            }

            if (cb_tiaozhuan.Checked)
            {
                newsModel.TiaoZhuan = 1;
            }
            else
            {
                newsModel.TiaoZhuan = 0;
            }

            if (cb_toutiao.Checked)
            {
                newsModel.TouTiao = 1;
            }
            else
            {
                newsModel.TouTiao = 0;
            }

            if (cb_jiacu.Checked)
            {
                newsModel.JiaCu = 1;
            }
            else
            {
                newsModel.JiaCu = 0;
            }

            if (fankui.Items[0].Selected == true)
            {
                newsModel.Feedback = 1;
            }
            else
            {
                newsModel.Feedback = 0;
            }

            if (sign.Items[0].Selected == true)
            {
                newsModel.Sign = 1;
            }
            else
            {
                newsModel.Sign = 0;
            }

            // newsModel.Tree = Int32.Parse(DDL_LanMu.SelectedValue);
            newsModel.Source = txt_source.Text;
            newsModel.Target = txt_target.Text;
            newsModel.Taxis = Int32.Parse(txt_Taxis.Text);
            //newsModel.AbbPic = txt_abbPic.Text;
            newsModel.Abstracts = txt_Abstracts.Text;
            newsModel.Keyword = txt_keyword.Text;
            newsModel.Content = editor.Value;
            newsModel.Author = txt_author.Text;
            newsModel.ReleaseDate = DateTime.Now;
            newsModel.Integral = Int32.Parse(txt_Integral.Text);
            newsModel.Types = Int32.Parse(DDL_LanMu.SelectedValue);
            newsModel.BrowseTime = 0;
            if (FileUpload1.FileName != "")
            {
                UploadImage(FileUpload1);
                newsModel.AbbPic = rel;
            }
            else
            {
                newsModel.AbbPic = lbl_img.Text;
            }
          
            //获取选中权限
            foreach (ListItem item in this.cbl_right.Items)
            {
                if (item.Selected == true)
                {
                    newsModel.BrowseRight += item.Value + ",";
                }
            }

            if (newsinfo.UpdateNews(newsModel) > 0)
            {
                Response.Write("<script>alert('更新成功');location.href=location.href;</script>");
            }
        }


        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="fileUpload"></param>
        private void UploadImage(FileUpload fileUpload)
        {
            bool fileOk = false;

            string size = fileUpload.PostedFile.ContentLength.ToString();

            //取得文件的扩展名,并转换成小写
            string fileExtension = System.IO.Path.GetExtension(fileUpload.FileName).ToLower();
            //限定只能上传jpg和gif图片
            string[] allowExtension = { ".jpg", ".gif" };
            //对上传的文件的类型进行一个个匹对
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {
                    fileOk = true;
                    break;
                }
            }
            if (!fileOk)
            {
                Response.Write("<script>alert('文件格式不正确！');location.href=location.href;</script>");
                return;
            }
            //对上传文件的大小进行检测，限定文件最大不超过1M
            if (fileUpload.PostedFile.ContentLength > 3082000)
            {
                fileOk = false;
            }

            if (fileOk)
            {
                try
                {
                    if (System.IO.Directory.Exists(Server.MapPath(filePath)) == false)//如果不存在就创建file文件夹
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(filePath));
                    }
                    String ReName = Guid.NewGuid().ToString();
                    rel = filePath + "/upload/" + ReName + fileExtension;
                    fileUpload.PostedFile.SaveAs(Server.MapPath(rel));
                    //hiddenImgUrl.Value = ReName + fileExtension;
                    //Image1.ImageUrl = SysConfiguration.UploadFilesPath + "Registration/" + hiddenImgUrl.Value;
                    //resultlbl.Text ="上传成功";
                }
                catch
                {

                    //resultlbl.Text = "上传失败";
                }
            }
            else
            {
                Response.Write("<script>alert('文件大小超出3M！');location.href=location.href;</script>");
                //JavaScript.Alert("文件大小超出3M！", this.Page);
                //resultlbl.Text = "文件类型或者文件大小超出3M或者文件类型不对";
            }
        }
    }
}